<template>
  <div>
    <BaseForm
      ref="searchForm"
      type="search"
      v-model:items="formItems"
      v-model:form="searchParams"
      @search="handleSearch"
      label-width="90"
    >
      <el-row type="flex">
        <el-col :span="8">
          <el-form-item label="内容类型">
            <el-radio-group v-model="searchParams.recordType">
              <el-radio-button label="1">舆情词</el-radio-button>
              <el-radio-button label="2">回复关键词</el-radio-button>
              <el-radio-button label="3">常见问题</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="内容分类">
            <el-select v-model="searchParams.typeId" style="width: 260px">
              <el-option :label="item.label" :value="item.value" v-for="item in cateList" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="内容">
            <el-input v-model="searchParams.opinionKey" style="width: 260px" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="统计时间">
            <el-date-picker
              v-model="searchParams.recordTime"
              type="datetimerange"
              range-separator="~"
              value-format="YYYY-MM-DD HH:ss:mm"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="[new Date(0, 0, 0, 0, 0, 0), new Date(0, 0, 0, 23, 59, 59)]"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="微信群名称">
            <el-input v-model="searchParams.wxGroupName" style="width: 260px" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供电单位">
            <selectPage
              style="width: 260px"
              :item="powerItem"
              v-model="searchParams.powerId"
              @update:modelValue="changePower"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供电线路">
            <selectPage
              style="width: 260px"
              :item="lineItem"
              v-model="searchParams.lineId"
              :search="searchParams.lineSearch"
              @update:modelValue="changeLine"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="台区">
            <selectPage
              style="width: 260px"
              :item="areaItem"
              v-model="searchParams.areaId"
              :search="searchParams.areaSearch"
              @update:modelValue="changeArea"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="片区/村社">
            <selectPage
              :item="communityItem"
              ref="CommunityRef"
              v-model="searchParams.communityId"
              :search="searchParams.communitySearch"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </BaseForm>

    <BaseTable
      ref="baseTable"
      :getTableDataFn="reportStatisticsService.opinionKeyRecordPageList"
      :searchParams="searchParams"
      :serial="true"
      :down="true"
      :downLoad="downLoad"
      serialLabel="触发次数排名"
    >
      <el-table-column prop="typeName" label="舆情分类" v-if="searchParams.recordType === '1'" />
      <el-table-column prop="opinionKey" label="舆情词" v-if="searchParams.recordType === '1'" />
      <el-table-column prop="typeName" label="关键词分类" v-if="searchParams.recordType === '2'" />
      <el-table-column prop="opinionKey" label="关键词" v-if="searchParams.recordType === '2'" />
      <el-table-column prop="typeName" label="常见问题分类" v-if="searchParams.recordType === '3'" />
      <el-table-column prop="opinionKey" label="常见问题" v-if="searchParams.recordType === '3'" />
      <el-table-column prop="totalNum" label="触发次数">
        <template #header>
          <span>触发次数</span>
          <SortTable
            :type="1"
            :sortTablekey="sortTablekey"
            @click="handleSort(1)"
            v-model:searchParams="searchParams"
            :handleSearch="handleSearch"
          >
          </SortTable>
        </template>
      </el-table-column>
      <el-table-column prop="groupNum" label="触发群聊数">
        <template #header>
          <span>触发群聊数</span>
          <SortTable
            :type="2"
            :sortTablekey="sortTablekey"
            @click="handleSort(2)"
            v-model:searchParams="searchParams"
            :handleSearch="handleSearch"
          ></SortTable>
        </template>
        <template #default="scope">
          {{ scope.row.groupNum }}
        </template>
      </el-table-column>

      <el-table-column prop="userNum" label="触发客户数"> </el-table-column>
      <el-table-column prop="communityNum" label="相关片区/村社数"> </el-table-column>
      <el-table-column prop="op" label="操作">
        <template #default="scope">
          <el-link :underline="false" link type="primary" size="small" @click.prevent="openGroupChat(scope.row)"
            >查看详情
          </el-link>
        </template>
      </el-table-column>
    </BaseTable>
    <GroupChat
      v-if="visibleGroupChat"
      v-model:dialogVisible="visibleGroupChat"
      :item="item"
      :recordType="searchParams.recordType"
    ></GroupChat>
  </div>
</template>

<script setup lang="ts">
import { reactive, onBeforeMount } from 'vue';
import SortTable from '@/components/sortTable.vue';
import GroupChat from './components/GroupChat.vue';
import { reportStatisticsService } from '@/api/reportStatistics';
import { commonService } from '@/api/common';

type DictionaryKeyString = 'opinionKeyManager' | 'cruxKeyManager' | 'commonManager';

export interface ListState {
  dictionaryKey: DictionaryKeyString;
}

const cateList = ref([]); // 内容分类列表
const communityList = ref([]);
import dayjs from 'dayjs';

const item = ref({});
const state = reactive<ListState>({
  dictionaryKey: 'opinionKeyManager',
});
const visibleGroupChat = ref(false);
const sortTablekey = ref(0);
const isDesc = ref(null);
const handleSort = (e) => {
  sortTablekey.value = e;
};
const formItems = ref([]);

const baseTable = ref(null);

const searchParams = ref({
  recordType: '1',
  recordTimeBegin: '',
  recordTimeEnd: '',
  typeId: '',
  opinionKeyId: '',
  opinionKey: '',
  wxGroupName: '',
  powerId: '',
  lineId: '',
  areaId: '',
  communityId: '',
  recordTime: [],

  //临时变量
  lineSearch: {
    powerId: '',
  },
  areaSearch: {
    powerId: '',
    lineId: '',
  },
  communitySearch: {
    powerId: '',
    lineId: '',
    areaId: '',
  },
});

const setDefaultDate = () => {
  const day = dayjs().get('date');
  // 如果是每个月的1号显示上个月的所有数据
  if (day === 1) {
    searchParams.value.recordTime = [
      dayjs().subtract(1, 'month').startOf('month').format('YYYY-MM-DD') + ' 00:00:00',
      dayjs().subtract(1, 'month').endOf('month').format('YYYY-MM-DD 23:59:59'),
    ];
  } else {
    searchParams.value.recordTime = [
      dayjs().startOf('month').format('YYYY-MM-DD') + ' 00:00:00',
      dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59'),
    ];
  }
};

onBeforeMount(() => {
  setDefaultDate();
});

// 内容类型改变，触发查询
watch(
  () => searchParams.value.recordType,
  (newVal) => {
    cateList.value = [];
    searchParams.value.communityId = '';
    searchParams.value.areaId = '';
    searchParams.value.powerId = '';
    searchParams.value.lineId = '';

    searchParams.value.wxGroupName = '';
    searchParams.value.opinionKey = '';
    searchParams.value.opinionKeyId = '';
    searchParams.value.typeId = '';
    searchParams.value.recordTime = [
      dayjs().startOf('month').format('YYYY-MM-DD') + ' 00:00:00',
      dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59'),
    ];

    if (newVal) {
      if (newVal === '1') {
        state.dictionaryKey = 'opinionKeyManager';
      }
      if (newVal === '2') {
        state.dictionaryKey = 'cruxKeyManager';
      }
      if (newVal === '3') {
        state.dictionaryKey = 'commonManager';
      }
      searchParams.value.typeId = '';
    }
    getListByParentKey();
    setDefaultDate();
    handleSearch();
  },
);

watch(
  () => searchParams.value.recordTime,
  (newVal) => {
    if (newVal != null) {
      searchParams.value.recordTimeBegin = dayjs(newVal[0]).format('YYYY-MM-DD 00:00:00');
      searchParams.value.recordTimeEnd = dayjs(newVal[1]).format('YYYY-MM-DD 23:59:59');
    }
  },
);

const powerItem = ref({
  name: '供电单位',
  key: 'powerId',
  funName: 'getByAreaQueryByPower',
  option: {
    name: 'powerName',
    value: 'powerId',
  },
});
const lineSearch = ref({
  powerId: searchParams.value.powerId,
});
const lineItem = ref({
  name: '供电线路',
  key: 'lineId',
  funName: 'getByAreaQueryByLine',
  option: {
    name: 'lineName',
    value: 'lineId',
  },
});
const areaSearch = ref({
  powerId: searchParams.value.powerId,
  lineId: searchParams.value.lineId,
});
const areaItem = ref({
  name: '台区',
  key: 'areaId',
  funName: 'getByAreaQueryByArea',
  option: {
    name: 'areaName',
    value: 'areaId',
  },
});

const communityItem = ref({
  name: '关联片区/村社',
  key: 'communityId',
  funName: 'getAllCommunity',
  option: {
    name: 'communityName',
    value: 'communityId',
  },
});

const changePower = (val: any) => {
  //线路搜索
  searchParams.value.lineSearch.powerId = val;
  //台区搜索赋值
  searchParams.value.areaSearch.powerId = val;
  searchParams.value.areaSearch.lineId = '';

  //社区搜索赋值
  searchParams.value.communitySearch.powerId = val;
  searchParams.value.communitySearch.lineId = '';
  searchParams.value.communitySearch.areaId = '';

  //公共搜索
  searchParams.value.lineId = '';
  searchParams.value.areaId = '';
  searchParams.value.communityId = '';
};
const changeLine = (val: any) => {
  searchParams.value.areaSearch.lineId = val;

  searchParams.value.communitySearch.lineId = val;
  searchParams.value.communitySearch.areaId = '';

  searchParams.value.areaId = '';
  searchParams.value.communityId = '';
};

const changeArea = (val: any) => {
  searchParams.value.communitySearch.areaId = val;

  searchParams.value.communityId = '';
};

const handleSearch = (data = { sort: undefined }, e = '') => {
  if (e != 'sort') sortTablekey.value = 0;
  if (data) isDesc.value = data.sort;
  else {
    isDesc.value = null;
    cateList.value = [];

    searchParams.value.communityId = '';
    searchParams.value.areaId = '';
    searchParams.value.powerId = '';
    searchParams.value.lineId = '';

    searchParams.value.wxGroupName = '';
    searchParams.value.opinionKey = '';
    searchParams.value.opinionKeyId = '';
    searchParams.value.typeId = '';

    if (!data) {
      searchParams.value.recordTime = [
        dayjs().startOf('month').format('YYYY-MM-DD 00:00:00'),
        dayjs().subtract(1, 'day').format('YYYY-MM-DD 23:59:59'),
      ];
    }
    getListByParentKey();
  }

  setTimeout(() => {
    baseTable.value.handleSearch({
      ...searchParams.value,
      orderField: sortTablekey.value,
      isDesc: data?.sort,
      date: undefined,
    });
  });
};
const downLoad = () => {
  reportStatisticsService
    .downLoad({
      data: {
        ...searchParams.value,
        orderField: sortTablekey.value,
        isDesc: isDesc.value,
        date: undefined,
      },
    })
    .then((res) => {
      var blob = new Blob([res]);
      let url = window.URL.createObjectURL(blob);
      let link = document.createElement('a');
      link.style.display = 'none';
      link.href = url;
      link.setAttribute('download', '高频触发内容统计.xls');
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    });
};
const getListByParentKey = () => {
  commonService.getListByParentKey({ data: state.dictionaryKey }).then((res) => {
    let data = res.data.map((e) => {
      return {
        label: e.dictionaryName,
        value: e.dictionaryValue,
      };
    });
    cateList.value.push(...data);
  });
};
const openGroupChat = (row) => {
  item.value = { ...row };
  visibleGroupChat.value = true;
};
onMounted(() => {
  getListByParentKey();
});
</script>

<style lang="scss" scoped>
:deep(.el-date-editor) {
  padding: 1px 10px;
}
</style>
